/**
 * 
 */
package com.nervytech.tutorcruise.db.dao.mysql.impl;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.nervytech.tutorcruise.db.dao.interfaces.IUserUuidDAO;
import com.nervytech.tutorcruise.db.dao.model.UserUuid;

/**
 * @author ADMIN
 * 
 */
@Repository("userUuidDAO")
public class UserUuidDAO extends JdbcDaoSupport implements IUserUuidDAO {

	private static final Logger logger = LoggerFactory
			.getLogger(UserUuidDAO.class);

	@Autowired
	UserUuidDAO(DataSource dataSource) {
		setDataSource(dataSource);
	}

	@Override
	public String getUuid(long userId, int type) {
		String uuidQuery = "SELECT UUID FROM USER_UUID WHERE USER_ID=" + userId
				+ " and type =" + type;

		logger.debug("Get uuid query : " + uuidQuery);

		return getJdbcTemplate().queryForObject(uuidQuery, String.class);
	}

	@Override
	public long getUserId(String uuId) {
		String uuidQuery = "SELECT USER_ID FROM USER_UUID WHERE UUID='" + uuId
				+ "'";

		logger.debug("Get uuid query : " + uuidQuery);

		return getJdbcTemplate().queryForObject(uuidQuery, Long.class);
	}

	@Override
	public void deleteUuid(String uuId) {
		String uuidDeleteQuery = "DELETE FROM USER_UUID WHERE UUID='" + uuId
				+ "'";

		logger.debug("Delete UUID Query : " + uuidDeleteQuery);

		getJdbcTemplate().execute(uuidDeleteQuery);
	}

	@Override
	public void saveUuid(UserUuid usrUuid) {

		String insertUuidQuery = "INSERT INTO USER_UUID VALUES(?,?,?,?)";

		logger.debug("Uuid query : " + insertUuidQuery);

		Object[] parms = { usrUuid.getUuid(), usrUuid.getUserId(),
				usrUuid.getType(), usrUuid.getCreatedTime() };

		getJdbcTemplate().update(insertUuidQuery, parms);

	}

	@Override
	public boolean isValidUuid(UserUuid usrUuid, String emailId) {
		String uuidQuery = "SELECT USER_ID FROM USER_UUID WHERE UUID=? AND USER_ID=? AND TYPE=?";

		Object[] parms = { usrUuid.getUuid(), usrUuid.getUserId(),
				usrUuid.getType() };
		logger.debug("Get uuid query : " + uuidQuery);

		try {
			getJdbcTemplate().queryForObject(uuidQuery, parms, Long.class);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
